<!-- CREATE 2022-08-23 -->
<!-- AUTHOR 伊玖OneNine -->

<script setup lang="ts">
import type { FormInst, FormItemRule, FormRules } from 'naive-ui'

const message = useMessage()
const formRef = ref<FormInst | null>(null)

// 表单数据类型
interface InfoType {
  username: string
  password: string
}

// 表单数据
const userinfo = ref<InfoType>({
  username: '',
  password: '',
})

// 验证规则
const rules: FormRules = {
  username: [
    {
      required: true,
      validator(rule: FormItemRule, value: string) {
        if (!value)
          return new Error('请输入用户名')

        return true
      },
      trigger: ['input', 'blur'],
    },
  ],
  password: [
    {
      required: true,
      validator(rule: FormItemRule, value: string) {
        if (!value)
          return new Error('请输入密码')

        return true
      },
      trigger: ['input', 'blur'],
    },
  ],
}

// 验证后提交表单
function handleValidateButtonClick(e: MouseEvent) {
  e.preventDefault()
  formRef.value?.validate((errors: any) => {
    if (!errors)
      message.success('验证成功')
  })
}

// 检测表单数据状态并启用按钮
const buttonEnable = computed<boolean>(() => {
  const name = userinfo.value.username
  const pass = userinfo.value.password
  return (name.length > 0) && (pass.length > 0)
})
</script>

<template>
  <n-card class="w-150" title="登录">
    <n-form ref="formRef" :model="userinfo" :rules="rules">
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="userinfo.username" placeholder="请输入用户名" @keydown.enter.prevent />
      </n-form-item>

      <n-form-item label="密码" path="password">
        <n-input v-model:value="userinfo.password" placeholder="请输入密码" type="password" show-password-on="mousedown" @keydown.enter.prevent />
      </n-form-item>

      <div class="w-full">
        <n-button type="info" class="w-full" :disabled="!buttonEnable" @click="handleValidateButtonClick">
          登录
        </n-button>
      </div>
    </n-form>
  </n-card>
</template>

<route lang="yaml">
meta:
  layout: login
</route>
